﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using MediaDataModel;
using MediaClient.Common;

namespace MediaClient.UserControls
{
    public partial class UCShelf : UserControl
    {
        #region private properties

        private short cellWidth = 20;

        private short cellHeight = 147;

        private short rowHeight = 0;

        private int cellSpliterWidth = 5;

        private int rowSpliterHeight = 12;

        private Color cSpliterColor = System.Drawing.SystemColors.ActiveCaption;

        private string shelfSeriesNumer = null;

        private ContextMenuStrip columnMenu = null;

        private DiscShelf currentDiscShelf = new DiscShelf();

        private Button currentDiscButton = null;

        private Button clickDisc = null;

        #endregion

        #region public properties

        public event EventHandler DiscClick;

        public event ThreadStart Loaded;

        public List<string> SpecialDiscList
        {
            get;
            set;
        }

        public Color ShelfColor
        {
            get { return this.cSpliterColor; }
            set { this.cSpliterColor = value; }
        }

        public event ShelfOperateHandler OperateShelf = null;

        #endregion

        public UCShelf()
        {
            InitializeComponent();
            this.rowHeight = short.Parse((this.cellHeight + this.rowSpliterHeight).ToString());
            
        }

        public UCShelf(string shelfSeriesNum)
        {
        }

        #region private methods

        #region Events

        private void UCShelf_Load(object sender, EventArgs e)
        {
            //this.Width = cellCount * 20 * cellCapcity + (cellCount - 1) * cellSpliterWidth + cellSpliterWidth * 4;

            InitializeForm();


        }

        private void btnCell_MouseMove(object sender, MouseEventArgs e)
        {
            Button btnCurrentCell = sender as Button;
            if (btnCurrentCell != null)
            {
                btnCurrentCell.FlatAppearance.BorderSize = 1;
                btnCurrentCell.FlatAppearance.BorderColor = System.Drawing.Color.Red;

            }
        }

        private void btnCell_MouseLeave(object sender, EventArgs e)
        {
            Button btnCurrentCell = sender as Button;
            if (btnCurrentCell != null)
            {
                if (clickDisc != btnCurrentCell)
                {
                    btnCurrentCell.FlatAppearance.BorderSize = 0;
                    btnCurrentCell.FlatAppearance.BorderColor = Color.White;
                }
            }
        }

        private void shelfColumn_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                Button o = sender as Button;
                currentDiscButton = o;
                SetColumnBorderColor(this.currentDiscButton,true);
                if (o != null)
                {
                    string[] shelfInfo = o.Name.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
                    if (shelfInfo.Length > 5)
                    {
                        o.ContextMenuStrip.Items[0].Image = global::MediaClient.Properties.Resources.盘片入库_1;
                        o.ContextMenuStrip.Items[0].Enabled = false;
                        o.ContextMenuStrip.Items[1].Image = global::MediaClient.Properties.Resources.盘片入库;
                        o.ContextMenuStrip.Items[1].Enabled = true;
                    }
                    else
                    {
                        
                        o.ContextMenuStrip.Items[0].Image = global::MediaClient.Properties.Resources.盘片入库;
                        o.ContextMenuStrip.Items[0].Enabled = true;
                        o.ContextMenuStrip.Items[1].Image = global::MediaClient.Properties.Resources.盘片入库_1;
                        o.ContextMenuStrip.Items[1].Enabled = false;
                    }
                    o.ContextMenuStrip.Show(Cursor.Position);

                }
            }
        }

        private void btnCell_Click(object sender, EventArgs e)
        {
            if (clickDisc != null)
                SetColumnBorderColor(clickDisc, false);
            this.clickDisc = sender as Button;
            if (this.clickDisc != null)
                SetColumnBorderColor(this.clickDisc, true);
            if (this.DiscClick != null)
                this.DiscClick(sender, e);
            
        }

        private void OperateShelf_Click(object sender, EventArgs e)
        {
            //操作离线柜
            ToolStripMenuItem oMenuItem = sender as ToolStripMenuItem;
            if (oMenuItem != null && this.OperateShelf != null)
            {
                string[] clumnInfo = currentDiscButton.Name.Split(new char[]{'_'},  StringSplitOptions.RemoveEmptyEntries);
                string discBarcode = "";
                if (oMenuItem.Name == "inMenuItem") //入库操作
                {
                    this.OperateShelf(clumnInfo[1], short.Parse(clumnInfo[2]), short.Parse(clumnInfo[3]), short.Parse(clumnInfo[4]), ShelfOperateType.CheckIn, ref discBarcode);
                    OperateDiscButton(currentDiscButton, discBarcode);
                }
                else if (oMenuItem.Name == "outMenuItem") //出库操作
                {
                    this.OperateShelf(clumnInfo[1], short.Parse(clumnInfo[2]), short.Parse(clumnInfo[3]), short.Parse(clumnInfo[4]), ShelfOperateType.CheckOut, ref discBarcode);
                    OperateDiscButton(currentDiscButton, discBarcode);
                }
            }
            SetColumnBorderColor(this.currentDiscButton,false);
        }

        private void columnMenu_Closed(object sender, ToolStripDropDownClosedEventArgs e)
        {
            SetColumnBorderColor(this.currentDiscButton, false);
        }

        #endregion

        #region methods

        private void InitializeForm()
        {
            InitializeMenu();
        }

        private void AddLoadingInfo()
        {

        }

        private void InitializeMenu()
        {
            columnMenu = new System.Windows.Forms.ContextMenuStrip();
            columnMenu.Closed += columnMenu_Closed;
            //入库菜单
            ToolStripMenuItem inMenuItem = new ToolStripMenuItem();
            inMenuItem.Name = "inMenuItem";
            inMenuItem.Image = global::MediaClient.Properties.Resources.盘片入库;
            inMenuItem.Text = "入 库";
            inMenuItem.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Bold); ;
            
            //inMenuItem.Name = "in_" + oShelf.SeriesNumber + "_" + rowIndex.ToString() + "_" + columnIndex.ToString();
            inMenuItem.Click += OperateShelf_Click;
            columnMenu.Items.Add(inMenuItem);

            //出库菜单
            ToolStripMenuItem outMenuItem = new ToolStripMenuItem();
            outMenuItem.Name = "outMenuItem";
            outMenuItem.Image = global::MediaClient.Properties.Resources.盘片入库;
            outMenuItem.Text = "出 库";
            outMenuItem.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Bold);
            //outMenuItem.Name = "out_" + oShelf.SeriesNumber + "_" + rowIndex.ToString() + "_" + columnIndex.ToString();
            outMenuItem.Click += OperateShelf_Click;
            columnMenu.Items.Add(outMenuItem);
        }

        private void ThreadMethod()
        {
            if (this.InvokeRequired == true)
            {
                this.BeginInvoke(new ThreadStart(ThreadMethod));
            }
            else
            {

                LoadShelf();
                //pnlShelf.Controls.re;
            }
        }

        private void LoadShelf()
        {
            if (this.shelfSeriesNumer == null)
                return;
            pnlShelf.Controls.Clear();
            using (CCTV6Entities db = new CCTV6Entities())
            {
                //var oShelf = new OfflineShelf { SeriesNumber = "wer", RowNumber = 5, ColumnNumber = 10, ColumnCapacity = 2 };
                var oShelf = db.OfflineShelves.Where(shelf => shelf.SeriesNumber == this.shelfSeriesNumer).SingleOrDefault();
                if (oShelf == null)
                {
                    Label lblNoShelf = new Label();
                    lblNoShelf.Dock = DockStyle.Fill;
                    lblNoShelf.Text = "没有匹配的离线柜信息。";
                    lblNoShelf.AutoSize = true;
                    lblNoShelf.Location = new Point(0, 0);
                    pnlShelf.Controls.Add(lblNoShelf);
                    return;
                }

                short rowCount = oShelf.RowNumber.Value;
                short cellCount = oShelf.ColumnNumber.Value;
                short cellCapcity = oShelf.ColumnCapacity.Value;
                this.Width = cellCount * 20 * cellCapcity + (cellCount - 1) * cellSpliterWidth + cellSpliterWidth * 4;
                this.Height = rowCount * this.rowHeight + this.rowSpliterHeight;
                List<DiscShelf> shelfDiscList = oShelf.DiscShelves.ToList();
                //this.SuspendLayout();
                for (short rowIndex = rowCount; rowIndex > 0; rowIndex--)
                {
                    Panel pnlRow = new Panel();
                    //pnlRow.SuspendLayout();
                    pnlRow.Dock = DockStyle.Top;
                    pnlRow.Height = this.rowHeight;
                    pnlRow.Width = this.Width;
                    pnlRow.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));


                    for (short columnIndex = cellCount; columnIndex > 0; columnIndex--)
                    {
                        if (columnIndex == cellCount)
                        {
                            Label lblCellSpliter = new Label();

                            lblCellSpliter.Text = "";
                            lblCellSpliter.BackColor = cSpliterColor;
                            lblCellSpliter.Dock = System.Windows.Forms.DockStyle.Left;
                            lblCellSpliter.Size = new System.Drawing.Size(cellSpliterWidth + 5, cellHeight);
                            pnlRow.Controls.Add(lblCellSpliter);
                        }
                        for (short columnOrderIndex = cellCapcity; columnOrderIndex > 0; columnOrderIndex--)
                        {
                            Button btnCell = new Button();

                            btnCell.Name = "btn_" + oShelf.SeriesNumber + "_" + rowIndex.ToString() + "_" + columnIndex.ToString() + "_" + columnOrderIndex.ToString();
                            btnCell.Size = new System.Drawing.Size(cellWidth, cellHeight);
                            btnCell.BackColor = System.Drawing.Color.Transparent;
                            btnCell.Dock = System.Windows.Forms.DockStyle.Left;
                            btnCell.ForeColor = Color.White;
                            btnCell.FlatAppearance.BorderSize = 0;
                            btnCell.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
                            btnCell.UseVisualStyleBackColor = false;
                            btnCell.BackgroundImage = global::MediaClient.Properties.Resources.货架无内容;
                            btnCell.Text = "";
                            string toolTipString = "";
                            btnCell.MouseUp += new System.Windows.Forms.MouseEventHandler(shelfColumn_MouseUp);
                            btnCell.Leave += OperateShelf_Click;
                            btnCell.ContextMenuStrip = this.columnMenu;
                            DiscShelf oDiscShel = shelfDiscList.Find(disc => disc.ShelfRowIndex.Value == rowIndex && disc.ShelfColumnIndex.Value == columnIndex && disc.ShelfColumnOrderIndex.Value == columnOrderIndex);
                            if (oDiscShel != null)
                            {
                                btnCell.MouseLeave += btnCell_MouseLeave;
                                btnCell.MouseMove += btnCell_MouseMove;

                                btnCell.Name += "_" + oDiscShel.DiscBarcode.ToString();
                                btnCell.Text = oDiscShel.BlueDisc.Name;

                                btnCell.Click += btnCell_Click;
                                if (SpecialDiscList != null && SpecialDiscList.Contains(oDiscShel.DiscBarcode) == true)
                                    btnCell.BackgroundImage = global::MediaClient.Properties.Resources.货架高亮显示;
                                else
                                    btnCell.BackgroundImage = global::MediaClient.Properties.Resources.货架有内容;
                                oDiscShel.BlueDisc.MediaPacks.ToList().ForEach(mediaPack =>
                                {
                                    toolTipString += "《" + mediaPack.Name + "》"+ "\r\n";
                                });

                            }

                            if (toolTipString != "")
                            {
                                toolTipString = toolTipString.Substring(0, toolTipString.Length - 2);
                                ttMovie.SetToolTip(btnCell, toolTipString);
                            }


                            pnlRow.Controls.Add(btnCell);
                        }

                        //添加间隔
                        Label lblLastCellSpliter = new Label();
                        lblLastCellSpliter.Text = "";
                        lblLastCellSpliter.BackColor = cSpliterColor;
                        lblLastCellSpliter.Dock = System.Windows.Forms.DockStyle.Left;
                        lblLastCellSpliter.Height = cellHeight;
                        if (columnIndex == 1)
                            lblLastCellSpliter.Width = cellSpliterWidth + 5;
                        else
                            lblLastCellSpliter.Width = cellSpliterWidth;

                        pnlRow.Controls.Add(lblLastCellSpliter);
                    }

                    Label lblRowSpliter = new Label();
                    lblRowSpliter.BackColor = cSpliterColor;
                    lblRowSpliter.Text = "";
                    lblRowSpliter.Dock = DockStyle.Top;
                    lblRowSpliter.Height = rowSpliterHeight;
                    pnlRow.Controls.Add(lblRowSpliter);

                    if (rowIndex == rowCount)
                    {
                        pnlRow.Height += this.rowSpliterHeight;

                        Label lblFrrstRowSpliter = new Label();
                        lblFrrstRowSpliter.BackColor = cSpliterColor;
                        lblFrrstRowSpliter.Text = "";
                        lblFrrstRowSpliter.Dock = DockStyle.Bottom;
                        lblFrrstRowSpliter.Height = rowSpliterHeight;
                        pnlRow.Controls.Add(lblFrrstRowSpliter);
                    }
                    this.pnlShelf.Height += pnlRow.Height;
                    this.pnlShelf.Width = this.Width;
                    //pnlRow.ResumeLayout(true);
                    this.pnlShelf.Controls.Add(pnlRow);
                }
                //this.ResumeLayout(true);
                //this.Height += pnlLoading.Height;
            }
            if (this.Loaded != null)
                this.Loaded();
        }

        private void SetColumnBorderColor(Button btn, bool addBorderColor)
        {
            if (btn != null)
            {
                if (addBorderColor == true)
                {
                    btn.FlatAppearance.BorderSize = 1;
                    btn.FlatAppearance.BorderColor = System.Drawing.Color.Red;
                }
                else
                {
                    btn.FlatAppearance.BorderSize = 0;
                    btn.FlatAppearance.BorderColor = Color.White;
                }
            }
        }

        private void OperateDiscButton(Button btn, string discBarcode)
        {
            if (btn == null) return;
            string[] columnInfo = btn.Name.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
            if (string.IsNullOrEmpty(discBarcode) == true)
            {
                btn.BackgroundImage = global::MediaClient.Properties.Resources.货架无内容;
                btn.MouseLeave -= btnCell_MouseLeave;
                btn.MouseMove -= btnCell_MouseMove;
                btn.Click -= btnCell_Click;
                btn.Text = "";
               // btn.
                if (columnInfo.Length > 5)
                    btn.Name = "btn_" + columnInfo[1] + "_" + columnInfo[2] + "_" + columnInfo[3] + "_" + columnInfo[4];
                ttMovie.SetToolTip(btn, "");
            }
            else
            {
                btn.MouseLeave += btnCell_MouseLeave;
                btn.MouseMove += btnCell_MouseMove;
                btn.Click += btnCell_Click;
                
                if (columnInfo.Length == 5)
                    btn.Name = "btn_" + columnInfo[1] + "_" + columnInfo[2] + "_" + columnInfo[3] + "_" + columnInfo[4]+ "_" + discBarcode;

                if (SpecialDiscList != null && SpecialDiscList.Contains(discBarcode) == true)
                    btn.BackgroundImage = global::MediaClient.Properties.Resources.货架高亮显示;
                else
                    btn.BackgroundImage = global::MediaClient.Properties.Resources.货架有内容;

                using (CCTV6Entities db = new CCTV6Entities())
                {
                    BlueDisc oDisc = db.BlueDiscs.Where(disc => disc.Barcode == discBarcode).SingleOrDefault();
                    if (oDisc != null)
                    {
                        btn.Text = oDisc.Name;
                        string toolTipString = "";
                        if (oDisc.MediaPacks != null)
                        {
                            foreach (var mediaPack in oDisc.MediaPacks)
                                toolTipString += "《" + mediaPack.Name + "》" + "\r\n";
                        }
                        if (toolTipString != "")
                        {
                            toolTipString = toolTipString.Substring(0, toolTipString.Length - 2);
                            ttMovie.SetToolTip(btn, toolTipString);
                        }
                    }
                }
                
            }
        }

        #endregion

        #endregion

        #region public methods

        public void DisplaySearchResult(string searchStr, string searchType)
        {
            pnlShelf.Controls.Clear();
            //InitializeShelf();
        }
        
        public void LoadShelfInfor(string shelfSeriesNumber)
        {
            this.shelfSeriesNumer = shelfSeriesNumber;
            Thread loadShelfThread = new Thread(ThreadMethod);
            loadShelfThread.Start();
        }

        #endregion


    }
}
